package com.cheney.weiboo.view;

import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.cheney.weiboo.R;
import com.cheney.weiboo.domain.Users;
import com.cheney.weiboo.service.UserService;
import com.cheney.weiboo.utils.ImageUtil;
import com.cheney.weiboo.utils.WeiboContext;
import com.mime.qweibo.examples.MyWeiboSync;
//帐号管理
public class AccountActivity extends ListActivity  implements OnItemClickListener,OnItemLongClickListener,OnClickListener{

	private ListView listView = null;
	private ImageView user_default_icon = null;
	private LinearLayout account_add_btn = null;
	private MyWeiboSync weibo;
	private UserService userService;
	private List<Users> userList = null;
	private UserAdapter userAdapter;
	private Drawable icon;
	private Users currentUser;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account);
		
		listView = getListView();
		user_default_icon = (ImageView)findViewById(R.id.user_default_headicon);//用户默认头像
		account_add_btn = (LinearLayout)findViewById(R.id.account_add_btn);//获得帐号点击button
		//设置监听器
		user_default_icon.setOnClickListener(this);
		account_add_btn.setOnClickListener(this);
		listView.setOnItemLongClickListener(this);
		
		
		userService = new UserService(this.getApplicationContext());//获得用户处理的Service
		//获得系统资源
		icon = getResources().getDrawable(R.drawable.icon);
		registerReceiver(broadcastReceiver, new IntentFilter("com.cheney.weibo.getVerifier"));
		
		userList = userService.getUserList(false);
		System.out.println(userList.size());
		SharedPreferences sp = getSharedPreferences("default_users", 0);
		String nick = sp.getString("user_default_nick", "");
		
		Users user = null;
		if(userList!=null&&userList.size()>0){
			if(nick!=""){
				user = userService.getUserByName(nick, userList);
			}
			if(user==null){
				user = userList.get(0);
			}
		}
		if(user!=null){
			currentUser = user;
			user_default_icon.setImageDrawable(user.getUserIcon());
		}
		Log.d("设置ListView", userList.size()+"");
		if(userList!=null&&userList.size()>0){
			userAdapter = new UserAdapter();
			listView.setAdapter(userAdapter);
		}
		
	}
	
	public class UserAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return userList.size();
		}

		@Override
		public Object getItem(int item) {
			return userList.get(item);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			//把Layout转换为View
			Log.d("设置ListView2", userList.size()+"");
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.account_item, null);
			ImageView headLogo = (ImageView)view.findViewById(R.id.headLogo);
			TextView nick = (TextView)view.findViewById(R.id.nick);
			TextView userName = (TextView)view.findViewById(R.id.userName);
			Users users = userList.get(position);
			
			headLogo.setImageDrawable(users.getUserIcon());
//			headLogo.setImageDrawable(getResources().getDrawable(R.drawable.icon));
			nick.setText(users.getUserName());
			userName.setText("@"+users.getUserId());
			
			return view;
		}
		
	}
	//设置view
	public void setUpView(){
		
	}
	
	//添加点击事件
	public void setUpClickLinstener(){
		
	}
	
	//创建一个广播接收器
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			//接收关于身份认证的广播
			if("com.cheney.weibo.getVerifier".equals(intent.getAction())){
				weibo = WeiboContext.getInstance();
				Bundle bundle = intent.getExtras();
				String verifer = bundle.getString("veryfier");//获得从授权页面返回的verifer
				System.out.println("verifer"+verifer);
				if(verifer!=null){
					weibo.getAccessToken(weibo.getTokenKey(), weibo.getTokenSecrect(), verifer);
					String userInfo = weibo.getUserInfo(weibo.getAccessTokenKey(), weibo.getAccessTokenSecrect());
					System.out.println("授权成功*************************************");
					try {
						//通过json对象进行解析
						JSONObject data = new JSONObject(userInfo).getJSONObject("data");
						System.out.println(data.toString());
						String headUrl = null;//头像的地址
						if(data.getString("head")!=null&&!"".equals(data.get("head"))){
							headUrl = data.getString("head")+"/100";
						}
						String userId = data.getString("name");
						String userName = data.getString("nick");
						Users users= new Users();
						users.setId(userId);
						users.setUserId(userId);
						users.setUserName(userName);
						users.setToken(weibo.getAccessTokenKey());
						users.setTokenSecret(weibo.getAccessTokenSecrect());
						//判断该用户是否存在
						long num;
						if(userService.isExits(userId)){
							Log.d("更新","更新");
							userService.update(userId, userName,  ImageUtil.getRoundBitmapFromUrl(headUrl, 15));
						}else {
							if(headUrl!=null&&!"".equals(headUrl)){
							 num = userService.saveUsers(users, ImageUtil.getBytesFromUrl(headUrl));
							Log.d("插入", ""+num+"有图");
							}else {
							num = userService.saveUsers(users,null);
							Log.d("插入", ""+num+"无图");
							}
							
						}
						//获得用户列表
						
						userList = userService.getUserList(false);
						userAdapter = new UserAdapter();
						userAdapter.notifyDataSetChanged();
						listView.setAdapter(userAdapter);
//						listView.setOnItemClickListener(AccountActivity.this);
						
						SharedPreferences sp = getSharedPreferences("default_users", 0);
						String nick = sp.getString("user_default_nick", "");
						
						Users defaultUser = null;
						if(userList!=null&&userList.size()>0){
							if(nick!=""){
								defaultUser = userService.getUserByName(nick, userList);
							}
							if(defaultUser==null){
								defaultUser = userList.get(0);
							}
						}
						
						if(defaultUser!=null){
							currentUser = defaultUser;
							user_default_icon.setImageDrawable(currentUser.getUserIcon());
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
			}
			
		}
		
	};
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		currentUser = userList.get(position);
		user_default_icon.setImageDrawable(currentUser.getUserIcon());
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int position,long arg3) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(AccountActivity.this);
		dialog.setTitle("选项");
		dialog.setCancelable(true);
		CharSequence[] items = new CharSequence[]{"删除帐号","取消"};
		dialog.setItems(items, new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
					switch(which){
					case 0:{
						String userId = userList.get(position).getId();
						userService.deleteById(userId);
						//清空默认登录用户
						SharedPreferences sr = getSharedPreferences("default_users",0);
						SharedPreferences.Editor ed = sr.edit();
						if(sr.getString("user_default_name", "").equals(userId)){
							ed.putString("user_default_nick", "");
							ed.putString("user_default_name","");
							ed.commit();
						}
						userList = userService.getUserList(false);
						userAdapter = new UserAdapter();
						userAdapter.notifyDataSetChanged();
						listView.setAdapter(userAdapter);
					}
					break;
					case 1: {
						
						
					}
					break;
					default:
					break;
					}
			}
		});
		dialog.show();
		return false;
	}

	@Override
	public void onClick(View v) {
				switch(v.getId()){
				case R.id.account_add_btn:{
					Log.d("帐号添加","帐号添加");
					weibo = WeiboContext.getInstance();
					weibo.getRequestToken();
					Intent intent = new Intent(AccountActivity.this,AuthorizeActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("url",weibo.getAuthorizeUrl());
					intent.putExtras(bundle);
					startActivity(intent);
				}
				break;
				case R.id.user_default_headicon:{
					Log.d("进入微博","进入微博");
					Intent intent = new Intent(AccountActivity.this,MainActivity.class);
					SharedPreferences sp = getSharedPreferences("default_users", 0);
					SharedPreferences.Editor editor = sp.edit();
					editor.putString("user_default_nick", currentUser.getUserName());
					editor.putString("user_default_name", currentUser.getUserId());
					editor.commit();
//					Bundle b = new Bundle();
//					b.putString("user_default_nick", currentUser.getUserName());
//					b.putString("user_default_name", currentUser.getUserId());
//					intent.putExtras(b);
					startActivity(intent);
				}
				break;
			}
	}
}
